<?php
/**
 * Created by PhpStorm.
 * User: 王松
 * Time: 2017/6/13 10:15
 */

namespace App\Project\Traits;

trait SearchAble
{
    protected $operatorMap = [
        'like' => 'like',
        '='    => 'eq',
        '!='   => 'neq',
        '<>'   => 'neq',
    ];

    /**
     * @param       $input
     * @param array $map
     * @return array
     */
    protected function parseSearchQueryToWhere($input, $map = [])
    {
        $where = [];

        if (empty($map) && !($map = $this->getSearchQueryMap())) {// =是赋值
            return $where;
        }

        $queries = array_intersect_key($input, $map);// 比较两个数组的键名，返回交集

        foreach ($queries as $key => $query) {

            if (($query !== '') && !is_null($query)) {// 全等判断
                $query = $this->parseQueryWithOperator($map[$key]['operator'], $query);

                $where[] = [$map[$key]['field'], $map[$key]['operator'], $query];
            }
        }

        return $where;
    }

    protected function getSearchQueryMap()
    {
        if (property_exists($this, 'searchQueryMap')) {
            return $this->searchQueryMap;
        }

        return [];
    }

    protected function parseQueryWithOperator($operator, $query)
    {
        $method = 'operator' . ucfirst($this->operatorMap[$operator]);

        if (method_exists($this, $method)) {
            return $this->$method($query);
        }

        return $query;
    }

    protected function operatorLike($query)
    {
        return '%' . $query . '%';
    }
}